package com.movecar.ui;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.listview.WaterFallListView;
import com.movecar.listview.WaterFallListView.IXListViewListener;
import com.movecar.model.CloudBeansBean;
import com.movecar.model.GroupBean;
import com.movecar.model.ThemeBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.PopupWindowAnimation;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.Constants;
import com.movecar.widget.CustomProgressDialog;
import com.movecar.widget.MyGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 浮云主题
 * 
 * @author Zhao.JQ
 * 
 */
public class ThemeActivity extends Activity implements IXListViewListener, OnClickListener {
	protected WaterFallListView mXList;
	private List<ThemeBean> mDataList;
	private List<ThemeBean> resultList;
	private CustomProgressDialog progressDialog = null;
	private ImageLoader imageLoader = null;
	private CloudBeansBean mCloudBeansBean;
	private String pageNo = "0";
	private boolean flgMore = false;
	private RelativeLayout main_relative;
	private ThemeMainAdapter mThemeMainAdapter;
	private View mainView;
	private LayoutInflater layoutInflater;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mainView = layoutInflater.inflate(R.layout.theme_main, null);
		setContentView(mainView);
		imageLoader = ImageLoader.getInstance();
		initView();
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initView() {
		TextView title = (TextView) findViewById(R.id.title);
		main_relative = (RelativeLayout) findViewById(R.id.main_relative);
		title.setText("hi主题");

		
		
		
		
		
		Button filtrate = (Button) findViewById(R.id.btn_right);
		filtrate.setBackgroundResource(R.drawable.btn_theme_filtrate);
		filtrate.setVisibility(View.VISIBLE);
		filtrate.setOnClickListener(this);
		mXList = (WaterFallListView) findViewById(R.id.theme_list);
		mXList.setPullLoadEnable(true);
		mXList.setPullRefreshEnable(true);
		mXList.setXListViewListener(this);
		mThemeMainAdapter = new ThemeMainAdapter(ThemeActivity.this, mXList);
		
		mXList.setAdapter(mThemeMainAdapter);
		startProgressDialog();
		getThemeData();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_right:
			Intent intent = new Intent(this, ThemeFiltrateActivity.class);
			startActivityForResult(intent, 0);
			break;
		default:
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				resultList.clear();
				flgMore = false;
				pageNo = "0";
				getThemeData();
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void getThemeData() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "themePageAndNew2")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("pageNo", pageNo));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				main_relative.setVisibility(View.VISIBLE);
				stopProgressDialog();
				Type type = new TypeToken<List<ThemeBean>>() {
				}.getType();
				Gson gson = new Gson();
				String result = (String) object;

				try {

					mDataList = gson.fromJson(result, type);
				} catch (Exception e) {
					return;
				}
				if (mDataList != null) {
					resultList = new ArrayList<ThemeBean>();
					if (flgMore) {
						resultList.clear();
						if (mDataList.size() == 0) {
							Alert.warn(ThemeActivity.this, "已经加载全部");
							if (!"1".equals(pageNo)) {
								pageNo = String.valueOf(Integer.parseInt(pageNo) - 1);
							} else {
								pageNo = "0";
							}
							resetXList();
						} else {
							resultList.clear();

							for (ThemeBean bean : mDataList) {
								resultList.add(bean);
							}
							mThemeMainAdapter.addItemLast(resultList);
							resetXList();

						}
					} else {

						if (mDataList.size() == 0) {
							Alert.warn(ThemeActivity.this, "目前无内容");

							resetXList();
						}
						resultList.clear();

						for (ThemeBean bean : mDataList) {
							resultList.add(bean);
						}
						mThemeMainAdapter.addItemTop(resultList);
						mThemeMainAdapter.notifyDataSetChanged();
						resetXList();
					}

				} else {
					stopProgressDialog();
					Alert.error(ThemeActivity.this, "系统异常");
				}

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();

				Alert.error(ThemeActivity.this, "与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	/**
	 *
	 * 
	 * @author Zhao.JQ
	 */
	@SuppressWarnings("unchecked")
	private void watchTheme(int position) {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "watchThemeNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("pmId", mDataList.get(position).getPmId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mCloudBeansBean = gson.fromJson(result, CloudBeansBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mCloudBeansBean && "0".equals(mCloudBeansBean.getResultCode())) {

					if (!TextUtils.isEmpty(mCloudBeansBean.getCoinAlert())) {
						new PopupWindowAnimation(mainView, ThemeActivity.this);
					}
				} else {
					Alert.warn(ThemeActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.warn(ThemeActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public class ThemeMainAdapter extends BaseAdapter {
		private Context mContext;
		private LinkedList<ThemeBean> mInfos;
		private LayoutInflater inflater;

		public ThemeMainAdapter(Context context, WaterFallListView xListView) {
			mContext = context;
			mInfos = new LinkedList<ThemeBean>();
			inflater = LayoutInflater.from(mContext);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			ViewHolder viewHolder;
			final ThemeBean mThemeBean = mInfos.get(position);

			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = inflater.inflate(R.layout.theme_main_item_new, null);

				viewHolder.title_name = (TextView) convertView.findViewById(R.id.title_name);
				viewHolder.title_button = (TextView) convertView.findViewById(R.id.title_button);
				viewHolder.theme_grid = (MyGridView) convertView.findViewById(R.id.theme_grid);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			ThemeMianGridViewAdapter grideAdapter = new ThemeMianGridViewAdapter(ThemeActivity.this,
					new ArrayList<Bitmap>());
			viewHolder.theme_grid.setAdapter(grideAdapter);
			viewHolder.title_button.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getApplicationContext(), ThemeDetailWaterFallActivity.class);
					intent.putExtra("ThemeId", mThemeBean.getPmId());
					intent.putExtra("detailLogo", mThemeBean.getDetailLogo());
					intent.putExtra("isRelate", mThemeBean.getIsRelate());
					startActivity(intent);

				}
			});
			return convertView;
		}

		class ViewHolder {
			TextView title_name, title_button;
			MyGridView theme_grid;

		}

		@Override
		public int getCount() {
			return mInfos.size();
		}

		@Override
		public Object getItem(int arg0) {
			return mInfos.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		public void addItemLast(List<ThemeBean> datas) {
			mInfos.addAll(datas);
		}

		public void addItemTop(List<ThemeBean> datas) {
			mInfos.clear();
			for (ThemeBean info : datas) {
				mInfos.addLast(info);
			}
		}
	}

	class ThemeMianGridViewAdapter extends BaseAdapter {

		Activity activity;
		private LayoutInflater inflater;
		ImageLoader imageLoader = null;
		ArrayList<Bitmap> picturesData = new ArrayList<Bitmap>();

		public ThemeMianGridViewAdapter(Activity activity, ArrayList<Bitmap> picturesData) {

			this.activity = activity;
			this.picturesData = picturesData;
			inflater = LayoutInflater.from(activity);

			imageLoader = ImageLoader.getInstance();
			imageLoader.init(Constants.imageLoaderConfiguration(activity));
		}

		@Override
		public int getCount() {

			return 4;
		}

		@Override
		public Object getItem(int arg0) {

			return picturesData.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return picturesData.size();
		}

		@Override
		public View getView(int position, View view, ViewGroup arg2) {
			View itemView = null;
			view = inflater.inflate(R.layout.theme_main_gride_item, arg2, false);
			itemView = view;

			ImageView theme_img = (ImageView) itemView.findViewById(R.id.theme_img);
			imageLoader.displayImage(AppConfig.HOST + resultList.get(0).getLogo(), theme_img,
					Constants.image_display_options, AppConfig.animateListener);
			return view;
		}

		class ViewHolder {

			ImageView mImageView;
		}

	}

	protected void resetXList() {

		mXList.setRefreshTime(new SimpleDateFormat("H:mm", Locale.CHINA).format(new Date()));
		mXList.stopRefresh();
		mXList.stopLoadMore();
	}

	@Override
	public void onRefresh() {
		resultList.clear();
		flgMore = false;
		pageNo = "0";
		getThemeData();

	}

	@Override
	public void onLoadMore() {
		flgMore = true;
		pageNo = String.valueOf(Integer.parseInt(pageNo) + 1);
		getThemeData();

	}
}
